from django.http import JsonResponse

from utils import requests_pro
from rest_framework.views import  APIView
from lxml import etree
from utils import orm
orm.orm_standby()
from dal import models

class SearchRequests(APIView):

    def post(self,request):

        message = {}

        try:
            keyword = request.data.get("keyword")
            username = str(request.data.get("username"))
            user_id = models.UserInfo.objects.get(username=username).pk
            session =requests_pro.session_requests_b()

            page = session.get(url="https://search.sina.com.cn/?q={}&c=news&sort=time".format(keyword))

            page.encoding = page.apparent_encoding

            page_text =page.text

            tree = etree.HTML(page_text)

            li_list = tree.xpath('//*[@id="result"]/div')

            for li in li_list:
                try:
                    title = li.xpath("./h2/a/text()")[0]
                    url = li.xpath("./h2/a/@href")[0]

                    if models.Search.objects.filter(title=title).exists() == False:
                        models.Search.objects.create(title=title,url=url,user_id=user_id)

                except:
                    pass

            message['code'] = 200

            return JsonResponse(message)
        except Exception as e:
            print(e)
            message['code'] = 444
            message['message'] = "更新失败"
            return JsonResponse(message)
